package daydayup.gateway.api;

import java.io.BufferedOutputStream;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import daydayup.gateway.api.pay.model.WXUnifiedPayResult;
import daydayup.gateway.api.pay.param.WXUnifiedPayParam;
import daydayup.gateway.api.pay.service.WxPayService;
import daydayup.gateway.api.pay.util.PayCommonUtil;

@Controller
@RequestMapping("/api/wx")
public class WxController {
	
	@Resource
	WxPayService wxPayService;

	@RequestMapping("/code")
	public void getCode(@RequestParam("appid") String appid, @RequestParam("url") String url) {
		WxUtils.getWxCodeUrl(appid, url);
	}
	
	@RequestMapping("/openid")
	public String getOpenId(@RequestParam("code") String code) {
		return WxUtils.getAcccessTokenUrl(WxUtils.APPID, WxUtils.API_KEY, code);
		
	}
	
	@RequestMapping("/prepay")
	public String doPay(HttpServletRequest request, HttpServletResponse response) {
		//此处为weixinPayMobile方法中拼接的参数
        String orderNo = request.getParameter("outTradeNo");
        String totalFee = request.getParameter("totalFee");
        //获取code 这个在微信支付调用时会自动加上这个参数无须设置
        String code = request.getParameter("code");
        //获取用户openID(JSAPI支付必须传openid)
        String openId = getOpenId(code);
        String notify_url =WxUtils.NOTIFY_URL+"/pay/notify/wechat";//回调接口
        String trade_type = "JSAPI";// 交易类型H5支付
		/**
		 * 填写预支付参数
		 */
		WXUnifiedPayParam param = this.build(request);
		WXUnifiedPayResult payResult = this.wxPayService.prepay(param);
		StringBuffer url = new StringBuffer();
		if("SUCCESS".equals(payResult.getReturn_code())){
			String resultCode = payResult.getResult_code();
            String errCodeDes = payResult.getErr_code_des();
            if("SUCCESS".equals(resultCode)){
            //获取预支付交易会话标识
            String prepay_id = (String) payResult.getPrepay_id();
            String prepay_id2 = "prepay_id=" + prepay_id;
            String packages = prepay_id2;
            SortedMap<Object, Object> finalpackage = new TreeMap<Object, Object>();
            String timestamp = new Date().toString();
            String nonceStr = payResult.getNonce_str();
            finalpackage.put("appId",  WxUtils.APPID);
            finalpackage.put("timeStamp", timestamp);
            finalpackage.put("nonceStr", nonceStr);
            finalpackage.put("package", packages); 
            finalpackage.put("signType", "MD5");
            //这里很重要  参数一定要正确 狗日的腾讯 参数到这里就成大写了
            //可能报错信息(支付验证签名失败 get_brand_wcpay_request:fail)
            String sign = PayCommonUtil.createSign("UTF-8", finalpackage,WxUtils.API_KEY);
            url.append("redirect:/weixin/payPage?");
            url.append("timeStamp="+timestamp+"&nonceStr=" + nonceStr + "&package=" + packages);
            url.append("&signType=MD5" + "&paySign=" + sign+"&appid="+ WxUtils.APPID);
            url.append("&orderNo="+orderNo+"&totalFee="+totalFee);
        }else{
           // logger.info("订单号:{}错误信息:{}",orderNo,errCodeDes);
            url.append("redirect:/weixin/error?code=0&orderNo="+orderNo);//该订单已支付
        }
    }else{
       // logger.info("订单号:{}错误信息:{}",orderNo,returnMsg);
        url.append("redirect:/weixin/error?code=1&orderNo="+orderNo);//系统错误
    }
		
    return url.toString();
    
	}
	
	WXUnifiedPayParam build(HttpServletRequest request) {
		WXUnifiedPayParam param = new WXUnifiedPayParam();
		//TODO 从请求中获取参数，并放入param
		
		return param;
	}
	
	//公众号H5支付主页
	@RequestMapping(value = "/payPage")
	    public String pay(HttpServletRequest request, HttpServletResponse response) throws Exception {
	    return "/pay/wx_pay";
	}
	
	@RequestMapping(value = "/payBack")
    public void WXPayBack(HttpServletRequest request, HttpServletResponse response){
        String resXml = "";
        try {
            //解析XML
            Map<String, String> map = MobileUtil.parseXml(request);
            String return_code = map.get("return_code");//状态
            String out_trade_no = map.get("out_trade_no");//订单号
            if (return_code.equals("SUCCESS")) {
                if (out_trade_no != null) {
                    //处理订单逻辑
                    //logger.info("微信手机支付回调成功订单号:{}",out_trade_no);
                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                }
            }else{
                //logger.info("微信手机支付回调失败订单号:{}",out_trade_no);
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
        } catch (Exception e) {
            //logger.error("手机支付回调通知失败",e);
             resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        try {
            // ------------------------------
            // 处理业务完毕
            // ------------------------------
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
}
